package com.wgz.medicalmanagement.infrastructure.security;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import javax.crypto.SecretKey;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

/**
 * JWT工具类，用于生成、验证和解析JWT令牌
 */
@Slf4j
@Component
public class JwtUtils {

    @Value("${app.security.jwt.secret}")
    private String secret;

    @Value("${app.security.jwt.expiration}")
    private long expiration;

    @Value("${app.security.jwt.remember-me-expiration}")
    private long rememberMeExpiration;
    
    @Value("${app.security.jwt.token-prefix}")
    private String tokenPrefix;

    /**
     * 根据用户详情生成JWT令牌
     */
    public String generateToken(UserDetails userDetails) {
        return generateToken(userDetails, false);
    }

    /**
     * 根据用户详情生成JWT令牌，可选是否"记住我"
     */
    public String generateToken(UserDetails userDetails, boolean rememberMe) {
        Map<String, Object> claims = new HashMap<>();
        long tokenValidity = rememberMe ? rememberMeExpiration : expiration;
        
        return Jwts.builder()
                .claims(claims)
                .subject(userDetails.getUsername())
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + tokenValidity))
                .signWith(getSignKey())
                .compact();
    }

    /**
     * 从令牌中获取用户名
     */
    public String extractUsername(String token) {
        try {
            return extractClaim(token, Claims::getSubject);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 检查令牌是否有效
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        try {
            final String username = extractUsername(token);
            return username != null && 
                   username.equals(userDetails.getUsername()) && 
                   !isTokenExpired(token);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取JWT令牌的有效期（毫秒）
     */
    public long getTokenExpirationMillis(boolean rememberMe) {
        return rememberMe ? rememberMeExpiration : expiration;
    }
    
    /**
     * 获取JWT令牌的过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    /**
     * 从令牌中获取指定声明
     */
    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    /**
     * 从令牌中获取所有声明
     */
    private Claims extractAllClaims(String token) throws JwtException {
        if (token != null && token.startsWith(tokenPrefix)) {
            token = token.substring(tokenPrefix.length());
        }
        
        return Jwts.parser()
                .verifyWith(getSignKey())
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    /**
     * 检查令牌是否已过期
     */
    private Boolean isTokenExpired(String token) {
        try {
            return extractExpiration(token).before(new Date());
        } catch (Exception e) {
            return true; // 解析失败时视为已过期
        }
    }

    /**
     * 从令牌中获取过期时间
     */
    private Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    /**
     * 获取签名密钥
     */
    private SecretKey getSignKey() {
        byte[] keyBytes = Decoders.BASE64.decode(secret);
        return Keys.hmacShaKeyFor(keyBytes);
    }
} 